package cn.edu.buu.hospital.service.impl;

import cn.edu.buu.hospital.entity.Hospital;
import cn.edu.buu.hospital.mapper.HospitalMapper;
import cn.edu.buu.hospital.service.HospitalService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalMapper hospitalMapper;

    @Override
    public void add(Hospital hospital) {
        // 检查医院名称是否已存在
        Hospital existingHospital = hospitalMapper.selectByName(hospital.getHospitalname());
        if (existingHospital != null) {
            throw new RuntimeException("医院名称已存在：" + hospital.getHospitalname());
        }
        hospitalMapper.insert(hospital);
    }

    @Override
    public void removeById(Long hospitalId) {
        // 检查该医院是否有关联的科室记录
        int deptCount = hospitalMapper.countDepartmentsByHospitalId(hospitalId);
        if (deptCount > 0) {
            throw new RuntimeException("该医院下还有" + deptCount + "个科室，无法删除！请先删除相关科室。");
        }
        hospitalMapper.deleteById(hospitalId);
    }

    @Override
    public void modify(Hospital hospital) {
        hospitalMapper.update(hospital);
    }

    @Override
    public Hospital findById(Long hospitalId) {
        return hospitalMapper.selectById(hospitalId);
    }

    @Override
    public List<Hospital> findAll() {
        return hospitalMapper.selectAll();
    }

    @Override
    public PageInfo<Hospital> find(int pageNum, int pageSize, Hospital condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<Hospital> hospitalList = hospitalMapper.selectByCondition(condition);
        return new PageInfo<>(hospitalList);
    }
}